package com.ssm.controller;

import com.ssm.domain.Role;
import com.ssm.domain.UserInfo;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    @PreAuthorize("hasAnyRole('22','ADMIN')")
    public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<UserInfo> list = userService.findAll();
        mv.addObject("userList", list);
        mv.setViewName("user-list");
        return mv;
    }

    @PostMapping("/save")
    public String save(UserInfo userInfo){
        userService.save(userInfo);
        return "redirect:findAll";
    }


    @PreAuthorize("authentication.principal.username=='11'")
    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable String id){
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = userService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show1");
        return mv;
    }
    @GetMapping("/findUserByIdAndAllRole/{id}")
    public ModelAndView findUserByIdAndAllRole(@PathVariable String id){
        ModelAndView mv = new ModelAndView();
        UserInfo byId = userService.findById(id);
       List<Role> list =  userService.findOtherRoles(id);
        mv.addObject("user", byId);
        mv.addObject("roleList", list);
        mv.setViewName("user-role-add");
        return mv;
    }
    @PostMapping("/addRoleToUser/{id}")
    public String addRoleToUser(@PathVariable String id , @RequestParam("ids") List<String> roleIds){
           userService.addRoleToUser(id,roleIds);
        return "redirect:../findAll";
    }

}
